//
//  SoftwareMenu.m
//  QuDownloader
//
//  Created by Thomas on 10/8/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "SoftwareMenu.h"
#import "QuDownloadController.h"
#import "SoftwareInstaller.h"

#define DEBUG_MODE false
static NSString  * bak_vers = nil;
static NSString  * _current_vers= nil;

@implementation SoftwareMenu
- (id) previewControlForItem: (long) item
{
	//NSLog(@"%@ %s", self, _cmd);
	NSString *resourcePath = nil;
	NSString *appPng = nil;
	NSString * theoption = [_options objectAtIndex:item];
	NSLog(@"%@",theoption);
			resourcePath = @"package";
			appPng = [[NSBundle bundleForClass:[self class]] pathForResource:resourcePath ofType:@"png"];

	if([theoption isEqualToString:@"Backup"])
	{
		resourcePath = @"timemachine";
		appPng = [[NSBundle bundleForClass:[self class]] pathForResource:resourcePath ofType:@"png"];
	}
	else if([theoption isEqualToString:@"Remove"])
	{
		resourcePath = @"trashempty";
		appPng = [[NSBundle bundleForClass:[self class]] pathForResource:resourcePath ofType:@"png"];
	}
	else if([theoption isEqualToString:@"Refresh"])
	{
		resourcePath = @"refresh";
		appPng = [[NSBundle bundleForClass:[self class]] pathForResource:resourcePath ofType:@"png"];
	}
	else if([theoption isEqualToString:@"Restore"])
	{
		resourcePath = @"timemachine";
		appPng = [[NSBundle bundleForClass:[self class]] pathForResource:resourcePath ofType:@"png"];
	}
	else if([theoption isEqualToString:@"Install"])
	{
		resourcePath = @"package";
		appPng = [[NSBundle bundleForClass:[self class]] pathForResource:resourcePath ofType:@"png"];
	}
	else if([theoption isEqualToString:@"Update"])
	{
		resourcePath = @"package";
		appPng = [[NSBundle bundleForClass:[self class]] pathForResource:resourcePath ofType:@"png"];
	}
	else if([theoption isEqualToString:@"Info"])
	{
		resourcePath = @"info";
		appPng = [[NSBundle bundleForClass:[self class]] pathForResource:resourcePath ofType:@"png"];
	}
	
	NSLog(@"%@", appPng);
	BRImageAndSyncingPreviewController *obj = [[BRImageAndSyncingPreviewController alloc] init];
	
	
	id sp = [BRImage imageWithPath:appPng];
	
	[obj setImage:sp];
	return (obj);
}

-(id)init{
	NSLog(@"init");
	if(DEBUG_MODE)
	{
		NSString *thelog = [NSString stringWithContentsOfFile:[NSString  stringWithFormat:@"/Users/frontrow/log.txt"]];
		thelog = [thelog stringByAppendingString:(@"\n")];
		[@"DEBUG MODE ON" writeToFile:@"/Users/frontrow/log.txt" atomically:YES];
		log = [NSFileHandle fileHandleForWritingAtPath:@"/Users/frontrow/Software.log"];
		[log retain];
		[log seekToEndOfFile];
	}
	//[self writeToLog:@"init"];
	return [super init];
}
- (void)dealloc
{
	//[self writeToLog:@"dealloc"];
	NSLog(@"dealloc");
	if(DEBUG_MODE)
	{
		
		
		[log closeFile];
		[log release];
	}
		
	[super dealloc];  
}

- (void)writeToLog:(NSString *)strLog
{
	if(DEBUG_MODE)
	{
		
		NSString *thelog = [NSString stringWithContentsOfFile:[NSString  stringWithFormat:@"/Users/frontrow/log.txt"]];
		thelog = [thelog stringByAppendingString:(@"\n \n %@",strLog)];
		[thelog writeToFile:@"/Users/frontrow/log.txt" atomically:YES];
		strLog = [strLog stringByAppendingString:@"\n"];
		NSData *data = [strLog dataUsingEncoding:NSASCIIStringEncoding];
		[log writeData:data];
	}
}

-(id)initWithIdentifier:(NSString *)initId withName:(NSString *)initName withURLStr:(NSString *)initurlstr withVers:(NSString *)initVers
{
	NSLog(@"===== initWithIdentifier =====");
	NSLog(@"%@, %@, %@, %@",initId,initName,initurlstr,initVers);
	identifier=[[NSString alloc]initWithString:initId];
	name=[[NSString alloc] initWithString:initName];
	urlstr=initurlstr;
	version=[[NSString alloc]initWithString:initVers];
	CFPreferencesSetAppValue(CFSTR("name"), (CFStringRef)[NSString stringWithString:name],kCFPreferencesCurrentApplication);
	CFPreferencesSetAppValue(CFSTR("urlstr"), (CFStringRef)[NSString stringWithString:urlstr],kCFPreferencesCurrentApplication);
	CFPreferencesSetAppValue(CFSTR("version"), (CFStringRef)[NSString stringWithString:version],kCFPreferencesCurrentApplication);
	
	[self checkVarious];
	
	[self addLabel:@"com.tomcool420.Software.SoftwareMenu"];
	[self setListTitle: name];
	
	_items = [[NSMutableArray alloc] initWithObjects:nil];
	_options = [[NSMutableArray alloc] initWithObjects:nil];
	
	
	//Adding option for Info
	[_options addObject:@"Info"];
	id item1 = [[BRTextMenuItemLayer alloc] init];
	[item1 setTitle:@"Info"];
	[_items addObject: item1];
	
	
	if(EXISTS==false)
	{
		//download and install plugin
		[_options addObject:@"Install"];
		id item2 = [[BRTextMenuItemLayer alloc] init];
		[item2 setTitle:@"Install"];
		[item2 setRightJustifiedText:version];
		[_items addObject:item2];
	}
	else
	{
		if (UPTODATE==false)
		{
			[_options addObject:@"Update"];
			id item3 = [[BRTextMenuItemLayer alloc] init];
			[item3 setTitle:@"Update"];
			[item3 setRightJustifiedText:version];
			[_items addObject:item3];
		}
		//This means it Exists
		//Offer option to Backup
		[_options addObject:@"Backup"];
		id item4 = [[BRTextMenuItemLayer alloc] init];
		[item4 setTitle:@"Backup"];
		[item4 setRightJustifiedText:_current_vers];
		[_items addObject:item4];
		
		//Offer option to Remove
		[_options addObject:@"Remove"];
		id item5 = [[BRTextMenuItemLayer alloc] init];
		[item5 setTitle:@"Remove"];
		[_items addObject:item5];
	}

	if (BAK_EXISTS)
	{
		//offer option to restore from backup
		[_options addObject:@"Restore"];
		id item6 = [[BRTextMenuItemLayer alloc] init];
		[item6 setTitle:@"Restore"];
		[item6 setRightJustifiedText:bak_vers];
		[_items addObject:item6];
	}

	[_options addObject:@"Refresh"];
	id item7 = [[BRTextMenuItemLayer alloc] init];
	[item7 setTitle:@"Refresh"];
	[item7 setRightJustifiedText:@"not working"];	
	[_items addObject:item7];
	
	id list = [self list];
	[list setDatasource: self];
	NSLog(@"%@",_current_vers);
	return self;
}
-(void)checkVarious
{
	
	NSLog(@"===== CheckVarious =====");
	
	NSString *frapPath= [[NSString alloc] initWithFormat:@"/System/Library/CoreServices/Finder.app/Contents/PlugIns/%@.frappliance/",name];
	NSString *bakPath= [[NSString alloc] initWithFormat:@"/Users/frontrow/Documents/Backups/%@.bak/",name];

	NSFileManager *manager = [NSFileManager defaultManager];
	
	if ([manager fileExistsAtPath:frapPath])
	{


		EXISTS = true;
		NSString * infoPath = [frapPath stringByAppendingString:@"Contents/Info.plist"];
		NSDictionary * info =[NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:infoPath]];
		_current_vers =[[NSString alloc]initWithString:[info objectForKey:@"CFBundleVersion"]];
		CFPreferencesSetAppValue(CFSTR("currentvers"), (CFStringRef)[NSString stringWithString:_current_vers],kCFPreferencesCurrentApplication);

		NSLog(@"version: %@ is installed; version %@ is most recent", _current_vers, version);
		
		if([_current_vers isEqualToString:version])
		{
			

			NSLog(@"frap is up to date");
			UPTODATE = true;
		}
		else
		{
			NSLog(@"you are not up to date");
			UPTODATE = false;
		}
		
	}
	else
	{
		EXISTS = false;
		CFPreferencesSetAppValue(CFSTR("currentvers"), (CFStringRef)[NSString stringWithString:@"0.0.0 - not installed"],kCFPreferencesCurrentApplication);
	}
	if([manager fileExistsAtPath:bakPath])
	{

		BAK_EXISTS = true;
		NSString *bakInfoPath = [bakPath stringByAppendingString:@"Contents/Info.plist"];
		NSDictionary * info =[NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:bakInfoPath]];
		
		bak_vers = [[NSString alloc]initWithString:[info objectForKey:@"CFBundleVersion"]];
		CFPreferencesSetAppValue(CFSTR("bakvers"), (CFStringRef)[NSString stringWithString:bak_vers],kCFPreferencesCurrentApplication);
	}
	else
	{
		BAK_EXISTS = false;
		bak_vers=[[NSString alloc]initWithString:@"0.0 -- not Backed Up"];
		CFPreferencesSetAppValue(CFSTR("bakvers"), (CFStringRef)[NSString stringWithString:bak_vers],kCFPreferencesCurrentApplication);
	}
}

-(long)defaultIndex
{
	return 0;
}

-(void)itemSelected:(long)fp8
{
	NSString *thename= (NSString *)(CFPreferencesCopyAppValue((CFStringRef)@"name", kCFPreferencesCurrentApplication));
	NSString *theurlstr= (NSString *)(CFPreferencesCopyAppValue((CFStringRef)@"urlstr", kCFPreferencesCurrentApplication));
	NSString *theversion = (NSString *)(CFPreferencesCopyAppValue((CFStringRef)@"version", kCFPreferencesCurrentApplication));
	NSString *thebackvers = (NSString *)(CFPreferencesCopyAppValue((CFStringRef)@"bakvers", kCFPreferencesCurrentApplication));
	NSString *thecurrentvers = (NSString *)(CFPreferencesCopyAppValue((CFStringRef)@"currentvers", kCFPreferencesCurrentApplication));
	NSLog(@"===== itemSelected =====");
	NSLog(@"thename: %@\ntheurlstr: %@\ntheversion: %@\nthebackvers: %@\nthecurrentvers: %@",thename,theurlstr,theversion,thebackvers,thecurrentvers);
	
	NSString * selectedOption = [_options objectAtIndex:fp8];
	NSLog(@"Selected option: %@",selectedOption);
	
	if (BAK_EXISTS)
	{
		NSLog(@"Backup Exists");
	}
	else
	{
		NSLog(@"Backup Does Not Exists");
	}
	if (EXISTS)
	{
		NSLog(@"Frap is Installed");
	}
	else
	{
		NSLog(@"Frap is not Installed");
	}

	//trying to set up the refresh option -- seems to Work -- Awesome
	
	if([selectedOption isEqualToString:@"Refresh"])
	{
		[self initWithIdentifier:@"101" withName:thename withURLStr:theurlstr withVers:theversion];
	}

	
	//Frappliance Information - Kinda Useless right now
	
	if([selectedOption isEqualToString:@"Info"])
	{
		BRAlertController *alert = [BRAlertController alertOfType:0
														   titled:[[NSString alloc] initWithFormat:@"%@ Info",thename]
													  primaryText:[[NSString alloc] initWithFormat:@"Current Version: %@\n Backup Version: %@\n Online Version: %@",thecurrentvers,thebackvers,theversion]
													secondaryText:nil];
		[[self stack] pushController: alert];
		return;
	}
	
	//Installation
	
	else if([selectedOption isEqualToString:@"Install"])
	{
		
		id newController = nil;
		newController =[[QuDownloadController alloc] init];
		[[self stack] pushController: newController];
		return;
	}
	
	// Update
	
	else if([selectedOption isEqualToString:@"Update"])
	{
		//removing Old frappliance
		
		[NSTask launchedTaskWithLaunchPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"remove" ofType:@"sh"] arguments:[NSArray arrayWithObject:thename]];
		
		//Downloading and Installing New Frappliance
		
		id newController = nil;
		newController =[[QuDownloadController alloc] init];
		[[self stack] pushController: newController];
		return;
	}
	
	// Remove
	
	 else if([selectedOption isEqualToString:@"Remove"])
	 {
		 [NSTask launchedTaskWithLaunchPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"remove" ofType:@"sh"] arguments:[NSArray arrayWithObject:thename]];
		 NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.4];
		 [NSThread sleepUntilDate:future];
		 [self initWithIdentifier:@"101"withName:thename withURLStr:theurlstr withVers:theversion];
		/* BRAlertController *alert = [BRAlertController alertOfType:0 
															titled:(@"Removed") 
													   primaryText:[[NSString alloc] stringWithFormat:@"%@ has been removed",thename] 
													 secondaryText:nil];
		 [[self stack] pushController: alert];*/
		 return;
	}
	
	 else if([selectedOption isEqualToString:@"Backup"])
	 {
		 
		if (BAK_EXISTS)
		{
			NSLog(@"Removing Old Backup");
			[NSTask launchedTaskWithLaunchPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"remove" ofType:@"sh"] arguments:[NSArray arrayWithObject:thename]];
		}
		[NSTask launchedTaskWithLaunchPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"backup" ofType:@"sh"] arguments:[NSArray arrayWithObject:name]];
		 NSLog(@"Backing Up");
		 NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.4];
		 [NSThread sleepUntilDate:future];
		 [self initWithIdentifier:@"101"withName:thename withURLStr:theurlstr withVers:theversion];
		 return;
	}
	
	//Restoring from backup
	
	 else if([selectedOption isEqualToString:@"Restore"])
	{
		//If it's Installed, Remove Current
		
		if (EXISTS)
		{
			[NSTask launchedTaskWithLaunchPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"remove" ofType:@"sh"] arguments:[NSArray arrayWithObject: thename]];
		}
		
		// Restore from Backup
		
		[NSTask launchedTaskWithLaunchPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"restore" ofType:@"sh"] arguments:[NSArray arrayWithObject:name]];
		
		NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.4];
		[NSThread sleepUntilDate:future];
		[self initWithIdentifier:@"101"withName:thename withURLStr:theurlstr withVers:theversion];
		return;
	}
	 
}
	 -(void)willBeBuried
	{
		NSLog(@"willBuried");
		[[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:[[self list] datasource]];
		[super willBeBuried];
	}
	 
	 -(void)willBePushed
	{
		NSLog(@"willBePushed");
		[super willBePushed];
	}
	 
	 -(void)willBePopped
	{
		NSLog(@"willBePopped");
		[[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:[[self list] datasource]];
		[super willBePopped];
	}
	 
- (void)refreshControllerForModelUpdate
{
	NSString *thename= (NSString *)(CFPreferencesCopyAppValue((CFStringRef)@"name", kCFPreferencesCurrentApplication));
	NSString *theurlstr= (NSString *)(CFPreferencesCopyAppValue((CFStringRef)@"urlstr", kCFPreferencesCurrentApplication));
	NSString *theversion = (NSString *)(CFPreferencesCopyAppValue((CFStringRef)@"version", kCFPreferencesCurrentApplication));
	[self initWithIdentifier:@"101" withName:thename withURLStr:theurlstr withVers:theversion];
}
	 
	 //	Data source methods:
	 
	 - (float)heightForRow:(long)row				{ return 0.0f; }
	 - (BOOL)rowSelectable:(long)row				{ return YES;}
	 - (long)itemCount							{ return (long)[_items count];}
	 - (id)itemForRow:(long)row					{ return [_items objectAtIndex:row]; }
	 - (long)rowForTitle:(id)title				{ return (long)[_items indexOfObject:title]; }
	 - (id)titleForRow:(long)row					{ return [[_items objectAtIndex:row] title]; }
	 
	 @end

